﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SiChuan.FormsApp.AppCode;
using SiChuan.FormsApp.AppCode.Helpers;
using Newtonsoft.Json;
using SiChuan.FormsApp.AppCode.Models;
using SiChuan.FormsApp.AppCode.Extensions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Net.Mime.MediaTypeNames;

namespace SiChuan.FormsApp {
    public partial class MainForm : Form {

        List<CaseListDto> patientList = new List<CaseListDto>();
        public static bool KEY_LOADING = false;
        bool KEY_UPDATE = false;// 上报锁

        public MainForm() {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e) {
            AddListViewPatientsColumns(true);
        }


        public async void AddListViewPatientsColumns(bool getData = false) {
            if (!KEY_LOADING) {

                KEY_LOADING = true;

                listViewPatients.Columns.Clear();
                listViewPatients.Items.Clear();

                listViewPatients.GridLines = true;
                listViewPatients.FullRowSelect = true;
                listViewPatients.View = View.Details;
                listViewPatients.MultiSelect = true;
                listViewPatients.CheckBoxes = true;

                listViewPatients.Columns.Add("NO", "序号", 50);
                listViewPatients.Columns.Add("Name", "患者姓名", 60);
                listViewPatients.Columns.Add("IdNo", "身份证号", 130);
                listViewPatients.Columns.Add("CaseName", "病种", 60);
                listViewPatients.Columns.Add("dType", "状态", 90);
                listViewPatients.Columns.Add("Remark", "备注", 100);

                // 
                if (getData) {

                    patientList = await "Syx/GetPatientList".ApiResponseAsync<List<CaseListDto>>(null);

                    if (patientList == null) {
                        KEY_LOADING = false;
                        return;
                    }
                    for (int i = 0; i < patientList.Count; i++) {
                        ListViewItem item = new ListViewItem();
                        item.UseItemStyleForSubItems = false;

                        item.SubItems.Clear();

                        DateTime diagnoseTime = DateTime.Now;

                        patientList[i].IsChecked = item.Checked = patientList[i].IsOk.IsNullOrWhiteSpace() ? true : patientList[i].IsOk == "上报成功" ? false : true;

                        patientList[i].id = item.SubItems[0].Text = (i + 1).ToString();
                        item.SubItems.Add(patientList[i].FOOD_NAME);
                        item.SubItems.Add(patientList[i].OUTPATIENT_ID);
                        item.SubItems.Add(patientList[i].IsOk);
                        item.SubItems.Add("");
                        item.SubItems.Add("");

                        if (i % 2 == 0) {
                            item.SubItems[0].BackColor = Color.FromArgb(242, 242, 242);
                            item.SubItems[1].BackColor = Color.FromArgb(242, 242, 242);
                            item.SubItems[2].BackColor = Color.FromArgb(242, 242, 242);
                            item.SubItems[3].BackColor = Color.FromArgb(242, 242, 242);
                            item.SubItems[4].BackColor = Color.FromArgb(242, 242, 242);
                            item.SubItems[5].BackColor = Color.FromArgb(242, 242, 242);
                        }
                        //if (diagnoseTime.AddHours(23) <= DateTime.Now) {
                        //    cdcPatient[i].checker = item.Checked = false;

                        //    item.SubItems[5].BackColor = Color.Cyan;
                        //    item.SubItems[5].Text = "已超23小时";
                        //}

                        //var mm = GetJsonobjForXmlobj(cdcPatient[i], true);
                        //if (mm == null) {
                        //    cdcPatient[i].checker = item.Checked = false;

                        //    item.SubItems[5].BackColor = Color.Orange;
                        //    item.SubItems[5].Text = "数据不对";
                        //}

                        listViewPatients.Items.Add(item);
                    }

                    KEY_LOADING = false;
                }
            }
        }

        private void buttonUpdate_Click(object sender, EventArgs e) {

            if (patientList != null && patientList.Count > 0) {
                var checkList = listViewPatients.CheckedItems;
                List<int> checkIndex = new List<int>();
                foreach (ListViewItem itemTxt in checkList) {
                    var index = Convert.ToInt32(itemTxt.Text);
                    checkIndex.Add(index);
                    itemTxt.SubItems[4].Text = "";
                }
                foreach (int ii in checkIndex) {
                    var pat = patientList[ii - 1];
                    BeginUpdateCase(pat.FOODID);
                    Task.WaitAny();
                }
            }
        }



        /// <summary>
        /// 上报病例
        /// </summary>
        /// <param name="foodid"></param>
        async void BeginUpdateCase(decimal foodid) {
            // 1、先获取要上报的xml
            var dataRes1 = await "Syx/GetSenderData".ApiGetSenderDataAsync(new Dictionary<string, object> { { "foodid", foodid } });
            string guid = Guid.NewGuid().ToString("N").ToLower();

            // 2、上传新病例
            // 2.1、如果返回有，直接上报
            if (dataRes1.Item1) {
                // 2.2、如果返回没有，上传新病例
                // 上传病例
                var txt = await guid.HisAddCaseAsync(dataRes1.Item2);
                var ss = txt.XmlToObjectForString<接口>();
                if (ss.操作状态 == "1") {
                    NlogHelper.Info("【新建病例】成功");
                    //var res2 = await "Syx/CreateNewCaseOk".ApiResponseAsync(new Dictionary<string, object> { { "foodid", foodid }, { "caseid", guid } });
                    //NlogHelper.Info("【新建病例.返回数据】成功");
                } else {
                    NlogHelper.Warn($"【新建病例】失败 - {ss.状态描述}");
                    return;
                }
            } else {
                guid = dataRes1.Item2;
            }

            if (Constants.IsDebug) {
                // 如果debug删除
                var txt = await guid.HisDelAsync();
                var ss = txt.XmlToObjectForString<接口>();
                //if (ss.操作状态 == "1") {
                //    NlogHelper.Info("【新建病例】成功");
                //    var res2 = await "Syx/CreateNewCaseOk".ApiResponseAsync(new Dictionary<string, object> { { "foodid", foodid }, { "caseid", guid } });
                //    NlogHelper.Info("【新建病例.返回数据】成功");
                //} else {
                //    NlogHelper.Warn($"【新建病例】失败 - {ss.状态描述}");
                //    return;
                //}

                NlogHelper.Warn($"【删除病例】 - {ss.状态描述}");
                return;
            }
            // 3、上报病例
            if (true) {
                var txt2 = await guid.HisUpdateCaseAsync();
                var ss = txt2.XmlToObjectForString<接口>();
                // 3.1、把返回的数据上报到服务器
                if (ss.操作状态 == "1") {
                    NlogHelper.Info("【上报病例】成功");
                    var res2 = await "Syx/CreateAndUpdateCaseOk".ApiResponseAsync(new Dictionary<string, object> { { "foodid", foodid }, { "caseid", guid } });
                    NlogHelper.Info("【上报病例.返回数据】成功");
                } else {
                    NlogHelper.Warn($"【上报病例】失败 - {ss.状态描述}");
                    //var res2 = await "Syx/UpdateCaseErr".ApiResponseAsync(new Dictionary<string, object> { { "foodid", foodid }, { "caseid", guid }, { "desc", ss.状态描述 } });
                    //NlogHelper.Info("【新建病例.返回数据】成功");
                    var txt = await guid.HisDelAsync();
                    var ss2 = txt.XmlToObjectForString<接口>();
                    NlogHelper.Warn($"【删除病例】 - {ss2.状态描述}");
                }
            }

        }

        private void button_reload_Click(object sender, EventArgs e) {
            AddListViewPatientsColumns(true);
        }
    }
}
